package com.homedo.odin.solution.service.bizservice.mng;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.CommonDataUtil;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.core.common.util.PatternUtils;
import com.homedo.odin.solution.contract.mng.SolutionAddReq;
import com.homedo.odin.solution.contract.mng.SolutionDelReq;
import com.homedo.odin.solution.contract.mng.SolutionDetailResp;
import com.homedo.odin.solution.contract.mng.SolutionListInfoResp;
import com.homedo.odin.solution.contract.mng.SolutionSkuDelReq;
import com.homedo.odin.solution.contract.mng.SolutionSkuImportReq;
import com.homedo.odin.solution.contract.mng.SolutionSkuResp;
import com.homedo.odin.solution.contract.mng.SolutionSortReq;
import com.homedo.odin.solution.contract.mng.SolutionStatusReq;
import com.homedo.odin.solution.contract.personal.treasure.AddScoreReq;
import com.homedo.odin.solution.enumcode.SqlEnum;
import com.homedo.odin.solution.enumcode.TemplateCodeEnum;
import com.homedo.odin.solution.enumcode.basic.BusinessTypeEnum;
import com.homedo.odin.solution.enumcode.basic.CommonTypeDataEnum;
import com.homedo.odin.solution.enumcode.basic.DeleteEnum;
import com.homedo.odin.solution.enumcode.basic.ErrorCodeEnum;
import com.homedo.odin.solution.enumcode.basic.FromTypeEnum;
import com.homedo.odin.solution.enumcode.operate.OperateTypeEnum;
import com.homedo.odin.solution.enumcode.operate.OperatorBusinessTypeEnum;
import com.homedo.odin.solution.enumcode.other.ScoreRuleEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionStateEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionTypeEnum;
import com.homedo.odin.solution.model.dto.SkuBean;
import com.homedo.odin.solution.model.dto.SolutionListInfoResponseBean;
import com.homedo.odin.solution.model.dto.SolutionSkuBean;
import com.homedo.odin.solution.model.entity.BrandOwner;
import com.homedo.odin.solution.model.entity.OperateTrace;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.SolutionSku;
import com.homedo.odin.solution.service.AttachmentServiceImpl;
import com.homedo.odin.solution.service.BrandOwnerServiceImpl;
import com.homedo.odin.solution.service.CommonTypeDataServiceImpl;
import com.homedo.odin.solution.service.OperateTraceServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.SolutionSkuServiceImpl;
import com.homedo.odin.solution.service.bizservice.personal.CommonBizService;
import com.homedo.odin.solution.service.bizservice.personal.UserTreasureBizService;
import com.homedo.odin.solution.service.common.HomedoService;
import com.homedo.odin.solution.util.SolutionBeansConvertUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: zhaoxudong
 * @date: 2018/3/27 17:35
 * @Description:
 */
@Service
public class MngSolutionsBizService {

    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    SolutionSkuServiceImpl solutionSkuService;
    @Autowired
    CommonTypeDataServiceImpl commonTypeDataService;
    @Autowired
    BrandOwnerServiceImpl brandOwnerService;
    @Autowired
    HomedoService homedoService;
    @Autowired
    AttachmentServiceImpl attachmentService;
    @Autowired
    OperateTraceServiceImpl operateTraceService;
    @Autowired
    CommonBizService commonBizService;
    @Autowired
    UserTreasureBizService userTreasureBizService;

    public SolutionListInfoResp solutions(Long solutionId, String solutionName, Integer solutionType,
            Integer isAdmitDownload, String expertName, Integer brandId, Integer status, String businessCode,
            String userName, Integer formType, String sortField, String sortType, Integer isDel, Integer pageNum,
            Integer pageSize) {
        String sortString = null;

        if (StringUtils.isNotBlank(sortField)) {
            if (!ArrayUtils.contains(
                    new String[]{"business_code", "page_view", "download_count", "sort", "create_time", "charges"},
                    sortField)
                    || !ArrayUtils.contains(new String[]{"asc", "desc"}, sortType)) {
                throw new BizException(Meta.CODE_451.getCode(), "排序信息不合法");
            } else {
                sortString = sortField + " " + sortType;
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Solution> info = new PageInfo<>(solutionService
                .querySolutionForPri(solutionId, solutionName, solutionType, isAdmitDownload, expertName, brandId,
                        status, businessCode, sortString, isDel, userName, formType));
        if (info.getList().isEmpty()) {
            return BeanUtils.transfrom(SolutionListInfoResp.class, info);
        }
        SolutionListInfoResp resp = BeanUtils.transfrom(SolutionListInfoResp.class, info);
        List<SolutionListInfoResponseBean> list = BeanUtils
                .batchTransform(SolutionListInfoResponseBean.class, info.getList());
        resp.setList(list);
        List<Long> solutionIdList = new ArrayList<Long>(list.size());
        for (SolutionListInfoResponseBean solution : list) {
            solutionIdList.add(solution.getSolutionId());
        }

        HashMap<Long, Integer> skuCountMap = new HashMap<>();
        HashMap<Long, Integer> shelveSkuCountMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(solutionIdList)) {
            skuCountMap = querySolutionSkuCountMap(solutionIdList);
            shelveSkuCountMap = querySolutionShelveSkuCountMap(solutionIdList);
        }

        if (CollectionUtils.isNotEmpty(list)) {
            HashMap<String, String> yjxtsxMap = commonTypeDataService
                    .getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
            HashMap<String, String> jzytMap = commonTypeDataService.getDataById(CommonTypeDataEnum.JZYT.getDbValue());
            int i = 0;
            for (SolutionListInfoResponseBean solutionInfo : list) {
                Integer skuCount = skuCountMap.get(solutionInfo.getSolutionId());
                Integer shelveSkuCount = shelveSkuCountMap.get(solutionInfo.getSolutionId());
                solutionInfo.setSkuCount(skuCount == null ? 0 : skuCountMap.get(solutionInfo.getSolutionId()));
                solutionInfo.setShelveSkuCount(
                        shelveSkuCount == null ? 0 : shelveSkuCountMap.get(solutionInfo.getSolutionId()));
                solutionInfo.setBuildingType(CommonDataUtil.mappedField(solutionInfo.getBuildingType(), jzytMap));
                solutionInfo.setFirstSysAttr(
                        CommonDataUtil.mappedField(String.valueOf(info.getList().get(i).getFirstSysAttr()), yjxtsxMap));
                i++;
                //查询品牌信息
                if (NumberHelper.validatePositive(solutionInfo.getBrandId())) {
                    BrandOwner brandOwner = brandOwnerService.findById(solutionInfo.getBrandId());
                    if (brandOwner != null) {
                        solutionInfo.setBrand(brandOwner.getBrandName());
                    }
                }
            }
        }
        return resp;
    }

    private HashMap<Long, Integer> querySolutionSkuCountMap(List<Long> solutionIdList) {

        List<Map<String, Object>> resultList = solutionSkuService.querySolutionSkuCountMap(solutionIdList);
        HashMap<Long, Integer> solutionSkuCountMap = new HashMap<Long, Integer>();
        if (CollectionUtils.isNotEmpty(resultList)) {
            for (Map<String, Object> map : resultList) {
                long solutionId = (long) map.get("solutionId");
                long count = (long) map.get("count");
                solutionSkuCountMap.put(solutionId, (int) count);
            }
        }
        return solutionSkuCountMap;
    }

    private HashMap<Long, Integer> querySolutionShelveSkuCountMap(
            List<Long> solutionIdList) {
        List<Map<String, Object>> resultList = solutionSkuService.querySolutionShelveSkuCountMap(solutionIdList);
        HashMap<Long, Integer> solutionSkuCountMap = new HashMap<Long, Integer>();
        if (CollectionUtils.isNotEmpty(resultList)) {
            for (Map<String, Object> map : resultList) {
                long solutionId = (long) map.get("solutionId");
                long count = (long) map.get("count");
                solutionSkuCountMap.put(solutionId, (int) count);
            }
        }
        return solutionSkuCountMap;
    }


    public SolutionDetailResp findSolution(Long solutionId) {
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "没有查到对应方案");
        }
        SolutionDetailResp resp = BeanUtils.transfrom(SolutionDetailResp.class, solution);
        resp.setFirstSysAttr(solution.getFirstSysAttr() == null ? null : String.valueOf(solution.getFirstSysAttr()));
        //查找sku信息
        List<SolutionSku> solutionSkus = solutionSkuService.selectListBySolutionId(solutionId);
        resp.setSolutionSkuList(BeanUtils.batchTransform(SolutionSkuBean.class, solutionSkus));
        //查询品牌信息
        if (NumberHelper.validatePositive(solution.getBrandId())) {
            BrandOwner brandOwner = brandOwnerService.findById(solution.getBrandId());
            if (brandOwner != null) {
                resp.setBrand(brandOwner.getBrandName());
            }
        }
        return resp;
    }

    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void add(SolutionAddReq request) {
        if (StringUtils.isBlank(request.getOperator())) {
            throw new BizException(Meta.CODE_451.getCode(), "操作人不能为空");
        }
        String businessCode = request.getBusinessCode();
        if (StringUtils.isNotBlank(businessCode)) {
            Solution solution = solutionService.getSolutionByBusinessCode(businessCode);
            if (solution != null) {
                throw new BizException(ErrorCodeEnum.IsExist.getDbValue(), "业务编码重复");
            }
        }
        if (SolutionTypeEnum.EXPERT_SOLUTION.getDbValue().equals(request.getSolutionType()) &&
                (StringUtils.isBlank(request.getExpertName()) || !NumberHelper
                        .validatePositive(request.getExpertId()))) {
            throw new BizException(Meta.CODE_451.getCode(), "系统方案的专家编号不能为空");
        }
        //提交类型(1:保存_已保存 2:提交_状态为待专家审核)
        Integer submitType = request.getSubmitType();
        if (submitType != 1 && submitType != 2) {
            throw new BizException(Meta.CODE_451.getCode(), "提交类型不支持(1:保存_已保存 2:提交_状态为待专家审核)!");
        }
        //建筑业态
        String buildType = request.getBuildingType();
        HashMap<String, String> jzytMap = commonTypeDataService.getDataById(CommonTypeDataEnum.JZYT.getDbValue());

        if (!CommonDataUtil.validate(buildType, jzytMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "建筑业态选项不合法!");
        }
        //一级系统属性
        Integer firstSysAttr = request.getFirstSysAttr();
        HashMap<String, String> yjxtsxMap = commonTypeDataService.getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstSysAttr), yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "一级系统属性选项不合法!");
        }
        //二级系统属性
        String secondSysTag = request.getSecondSysAttr();
        if (!CommonDataUtil.validate(secondSysTag, yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "二级系统属性选项不合法!");
        }

        Solution solution = BeanUtils.transfrom(Solution.class, request);
        if (null == solution) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "信息无法转换");
        }
        solution.setCreateTime(new Date());
        solution.setCreateUserName(request.getOperator());

        //如果新增方案为系统专家方案时需要专家审核,如果为产品方案时,则系统直接跳过审核,状态变为审核通过
        Integer status;
        String traceDetail;
        if (SolutionTypeEnum.EXPERT_SOLUTION.getDbValue().equals(request.getSolutionType())) {
            status = submitType == 1 ? SolutionStateEnum.SAVED.getDbValue()
                    : SolutionStateEnum.PENDINGAUDIT.getDbValue();
            traceDetail = "新增系统方案记录";
        } else {
            status = SolutionStateEnum.AUDITSUCCESS.getDbValue();
            traceDetail = "新增产品方案,状态系统自动变更";
        }
        solution.setStatus(status);
        solution.setFormType(FromTypeEnum.BACK_UPLOAD.getDbValue());
        Long solutionId = solutionService.addSolution(solution);
        //增加方案附件详细信息
        String attachment = solution.getAttachment();
        attachmentService.addAttachment(attachment, solutionId, BusinessTypeEnum.SOLUTION.getDbValue());

        //新增记录
        OperateTrace operateTrace = new OperateTrace();
        String detail = String
                .format(traceDetail + ",方案编号%s,状态%s->%s", solutionId, SolutionStateEnum.SAVED.getDbValue(), status);
        operateTrace.setSolutionId(solutionId);
        operateTrace.setBusinessType(OperatorBusinessTypeEnum.SOLUTION_INFO.getDbValue());
        operateTrace.setCreateTime(new Date());
        operateTrace.setDetail(detail);
        operateTrace.setOperator(request.getOperator());
        operateTrace.setOperatType(OperateTypeEnum.ADD.getDbValue());
        operateTrace.setFromState(SolutionStateEnum.SAVED.getDbValue());
        operateTrace.setToState(status);

        operateTraceService.addOperateTrace(operateTrace);
    }

    public void del(SolutionDelReq req) {
        Solution solution = solutionService.findBySolutionId(req.getSolutionId());
        if (!ArrayUtils.contains(new Integer[]{DeleteEnum.IS_DEL.getDbValue(), DeleteEnum.NOT_DEL.getDbValue()},
                req.getIsDel())) {
            throw new BizException(Meta.CODE_451.getCode(), "删除状态不合规！");
        }
        if (solution == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该方案信息不存在!");
        }
        if (req.getIsDel().equals(DeleteEnum.IS_DEL.getDbValue()) &&
                solution.getStatus().intValue() == SolutionStateEnum.SHELVE.getDbValue()) {
            throw new BizException(Meta.CODE_451.getCode(), "该方案在上架中，无法删除!");
        }
        solutionService.updateDel(req.getSolutionId(), req.getIsDel());
    }

    public void updateSort(SolutionSortReq req) {
        if (req.getSolutionId() == null || req.getSolutionId() <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        if (req.getSort() == null) {
            throw new BizException(Meta.CODE_451.getCode(), "sort不合规");
        }
        Integer count = solutionService.updateSort(req.getSolutionId(), req.getSort());
        if (count <= 0) {
            throw new BizException(SqlEnum.FAIL.getCode(), "没有数据更新成功！");
        }
    }

    public void edit(SolutionAddReq request) {
        Solution solution = solutionService.findBySolutionId(request.getSolutionId());
        if (solution == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该方案不存在");
        }
        String businessCode = request.getBusinessCode();
        if (StringUtils.isNotBlank(businessCode) && !businessCode.equals(solution.getBusinessCode())) {
            Solution exsitSolution = solutionService.getSolutionByBusinessCode(businessCode);
            if (exsitSolution != null) {
                throw new BizException(ErrorCodeEnum.IsExist.getDbValue(), "业务编码重复!");
            }
        }
        //状态为待专家审核以及已上架时 不允许编辑
        Integer solutionStatus = solution.getStatus();
        if (ArrayUtils.contains(new int[]{SolutionStateEnum.SHELVE.getDbValue()}, solutionStatus)) {
            throw new BizException(Meta.CODE_451.getCode(), "状态为待专家审核以及已上架, 不允许编辑!");
        }
			/*if(!solutionEditBean.getSolutionType().equals(SOLUTION.getSolutionType())){
				return ResponseBuilder.build(ReturnCode.NOT_SUPPORTTED, "方案类型不允许切换!", null);
			}*/
        if (solution.getFormType().intValue() == FromTypeEnum.FRONT_UPLOAD.getDbValue()
                && !solution.getSolutionType().equals(request.getSolutionType())) {
            throw new BizException(Meta.CODE_451.getCode(), "前台上传的方案方案类型不允许修改!");
        }
        if (solution.getFormType().intValue() == FromTypeEnum.FRONT_UPLOAD.getDbValue() && solution.getSolutionType()
                .equals(SolutionTypeEnum.EXPERT_SOLUTION.getDbValue())
                && !solution.getExpertId().equals(request.getExpertId())) {
            throw new BizException(Meta.CODE_451.getCode(), "前台上传的专家方案专家归属不允许修改!");

        }
        if (solution.getFormType().intValue() == FromTypeEnum.FRONT_UPLOAD.getDbValue() && solution.getSolutionType()
                .equals(SolutionTypeEnum.BRAND_SOLUTION.getDbValue())
                && !solution.getBrandId().equals(request.getBrandId())) {
            throw new BizException(Meta.CODE_451.getCode(), "前台上传的产品方案品牌不允许修改!");
        }
        //类型为专家方案时 关联的专家必填
        if (SolutionTypeEnum.EXPERT_SOLUTION.getDbValue().equals(request.getSolutionType())
                && (StringUtils.isBlank(solution.getExpertName()) || !NumberHelper
                .validatePositive(solution.getExpertId()))) {
            throw new BizException(Meta.CODE_451.getCode(), "类型为专家方案时 关联的专家必填!");
        }
        SolutionBeansConvertUtil.convert(request, solution);
        String buildType = solution.getBuildingType();//建筑业态
        HashMap<String, String> jzytMap = commonTypeDataService.getDataById(CommonTypeDataEnum.JZYT.getDbValue());

        if (!CommonDataUtil.validate(buildType, jzytMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "建筑业态选项不合法!");
        }

        Integer firstSysAttr = solution.getFirstSysAttr();//一级系统属性
        HashMap<String, String> yjxtsxMap = commonTypeDataService.getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstSysAttr), yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "一级系统属性选项不合法!");
        }

        String secondSysTag = solution.getSecondSysAttr();//二级系统属性
        if (!CommonDataUtil.validate(secondSysTag, yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "二级系统属性选项不合法!");
        }

        solution.setCreateUserName(request.getOperator());
        solution.setLastModifiedTime(new Date());
        solutionService.editSolution(solution);

        //先删除原有方案附件
        attachmentService.delAttachmentByBusinessId(solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue());
        //增加方案附件详细信息
        String attachment = solution.getAttachment();
        attachmentService.addAttachment(attachment, solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue());

        //新增记录
        OperateTrace operateTrace = new OperateTrace();
        String detail = String
                .format("编辑方案记录,方案编号%s,状态%s->%s", solution.getSolutionId(), solution.getStatus(), solution.getStatus());
        operateTrace.setSolutionId(solution.getSolutionId());
        operateTrace.setCreateTime(new Date());
        operateTrace.setBusinessType(OperatorBusinessTypeEnum.SOLUTION_INFO.getDbValue());
        operateTrace.setDetail(detail);
        operateTrace.setOperator(request.getOperator());
        operateTrace.setOperatType(OperateTypeEnum.UPDATE.getDbValue());
        operateTrace.setFromState(solution.getStatus());
        operateTrace.setToState(solution.getStatus());

        operateTraceService.addOperateTrace(operateTrace);
    }

    public void status(SolutionStatusReq req) {
        if (StringUtils.isBlank(req.getOperator())) {
            throw new BizException(Meta.CODE_451.getCode(), "操作人不能为空");
        }
        Long solutionId = req.getSolutionId();
        if (solutionId == null || solutionId <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        if (!ArrayUtils.contains(new Integer[]{SolutionStateEnum.AUDITSUCCESS.getDbValue(),
                SolutionStateEnum.AUDITFAIL.getDbValue(), SolutionStateEnum.UNSHELVE.getDbValue(),
                SolutionStateEnum.SHELVE.getDbValue()}, req.getStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "状态不合规");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在");
        }
        //下架
        if (req.getStatus().equals(SolutionStateEnum.UNSHELVE.getDbValue())) {
            unShelve(req, solution);
            return;
        }
        //上架
        if (req.getStatus().equals(SolutionStateEnum.SHELVE.getDbValue())) {
            shelve(req, solution);
            return;
        }
        //审核状态
        auditStatus(req, solution);
    }

    /**
     * 审核状态修改
     */
    private void auditStatus(SolutionStatusReq req, Solution solution) {
        if (req.getStatus().equals(SolutionStateEnum.AUDITFAIL.getDbValue()) &&
                StringUtils.isBlank(req.getAuditOpinion())) {
            throw new BizException(Meta.CODE_451.getCode(), "审核不通过时，审核意见不能为空!");
        }
        if (req.getStatus().equals(SolutionStateEnum.AUDITSUCCESS.getDbValue())) {
            req.setAuditOpinion(null);
        }
        if (!ArrayUtils.contains(new Integer[]{SolutionStateEnum.BACKAUDIT.getDbValue()}, solution.getStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "当前状态不支持该操作!");
        }

        solutionService
                .handleStateChange(solution.getSolutionId(), solution.getStatus(), req.getStatus(), req.getOperator(),
                        req.getAuditOpinion());

        //新增记录
        OperateTrace operateTrace = new OperateTrace();
        String detail = String
                .format("审核用户上传方案,方案编号%s,状态%s->%s", solution.getSolutionId(), solution.getStatus(), req.getStatus());
        operateTrace.setSolutionId(solution.getSolutionId());
        operateTrace.setCreateTime(new Date());
        operateTrace.setBusinessType(OperatorBusinessTypeEnum.SOLUTION_INFO.getDbValue());
        operateTrace.setDetail(detail);
        operateTrace.setOperator(req.getOperator());
        operateTrace.setOperatType(OperateTypeEnum.UPDATE.getDbValue());
        operateTrace.setFromState(solution.getStatus());
        operateTrace.setToState(req.getStatus());

        operateTraceService.addOperateTrace(operateTrace);
        //审核通过增加vip积分
        if (req.getStatus().equals(SolutionStateEnum.AUDITSUCCESS.getDbValue()) && NumberHelper
                .validatePositive(solution.getUserId())) {
            homedoService
                    .addSolutionVipIntegral(solution.getUserId(), solution.getCreateTime(), solution.getSolutionId());
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("@@userName", solution.getUserName());
            paramMap.put("@@bizId", solution.getSolutionId().toString());
            paramMap.put("@@solution", solution.getSolutionName());
            commonBizService.sentMessage(paramMap, solution.getUserId(), 0, TemplateCodeEnum.solution_pass.toString());
            //增加积分
            AddScoreReq addScoreReq = new AddScoreReq();
            addScoreReq.setUserId(solution.getUserId());
            addScoreReq.setBizCode(solution.getSolutionId().toString());
            addScoreReq.setType(ScoreRuleEnum.Sol.getType());
            commonBizService.addScore(addScoreReq);
        }
        if (req.getStatus().equals(SolutionStateEnum.AUDITFAIL.getDbValue()) && NumberHelper
                .validatePositive(solution.getUserId())) {
            Map<String, String> paramMap = Maps.newHashMap();
            paramMap.put("@@userName", solution.getUserName());
            paramMap.put("@@bizId", solution.getSolutionId().toString());
            paramMap.put("@@solution", solution.getSolutionName());
            commonBizService
                    .sentMessage(paramMap, solution.getUserId(), 0, TemplateCodeEnum.solution_nopass.toString());
        }
    }

    /**
     * 方案上架
     */
    private void shelve(SolutionStatusReq req, Solution solution) {
        if (!ArrayUtils.contains(new Integer[]{SolutionStateEnum.UNSHELVE.getDbValue(),
                SolutionStateEnum.AUDITSUCCESS.getDbValue()}, solution.getStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "当前状态不支持该操作!");
        }
        //更新发布时间
        solution.setShelveTime(new Date());
        solutionService.editSolution(solution);
        //更新状态
        solutionService
                .handleStateChange(req.getSolutionId(), solution.getStatus(), SolutionStateEnum.SHELVE.getDbValue(),
                        req.getOperator(), null);
        //新增记录
        OperateTrace operateTrace = new OperateTrace();
        String detail = String.format("发布上架,方案编号%s,状态%s->%s", solution.getSolutionId(), solution.getStatus(),
                SolutionStateEnum.SHELVE.getDbValue());
        operateTrace.setSolutionId(solution.getSolutionId());
        operateTrace.setCreateTime(new Date());
        operateTrace.setBusinessType(OperatorBusinessTypeEnum.SOLUTION_INFO.getDbValue());
        operateTrace.setDetail(detail);
        operateTrace.setOperator(req.getOperator());
        operateTrace.setOperatType(OperateTypeEnum.UPDATE.getDbValue());
        operateTrace.setFromState(solution.getStatus());
        operateTrace.setToState(SolutionStateEnum.SHELVE.getDbValue());

        operateTraceService.addOperateTrace(operateTrace);
    }

    /**
     * 方案下架
     */
    private void unShelve(SolutionStatusReq req, Solution solution) {
        if (!ArrayUtils.contains(new int[]{SolutionStateEnum.SHELVE.getDbValue()}, solution.getStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "当前状态不支持该操作!");
        }
        solutionService
                .handleStateChange(req.getSolutionId(), solution.getStatus(), SolutionStateEnum.UNSHELVE.getDbValue(),
                        req.getOperator(), null);

        //新增记录
        OperateTrace operateTrace = new OperateTrace();
        String detail = String.format("发布下架,方案编号%s,状态%s->%s", solution.getSolutionId(), solution.getStatus(),
                SolutionStateEnum.UNSHELVE.getDbValue());
        operateTrace.setSolutionId(solution.getSolutionId());
        operateTrace.setCreateTime(new Date());
        operateTrace.setBusinessType(OperatorBusinessTypeEnum.SOLUTION_INFO.getDbValue());
        operateTrace.setDetail(detail);
        operateTrace.setOperator(req.getOperator());
        operateTrace.setOperatType(OperateTypeEnum.UPDATE.getDbValue());
        operateTrace.setFromState(solution.getStatus());
        operateTrace.setToState(SolutionStateEnum.UNSHELVE.getDbValue());

        operateTraceService.addOperateTrace(operateTrace);
    }

    /**
     * MNG_根据方案id查询sku列表
     */
    public List<SolutionSkuResp> getSkus(String solutionIds) {
        String[] arr = solutionIds.split(";");
        List<Long> solutionIdsList = Arrays.stream(arr).filter(
                //留下非空字符串，并且是数字的
                str -> StringUtils.isNotBlank(str) && PatternUtils.isNumber(str)).map(
                //字符转换数字
                str -> Long.parseLong(str)).collect(Collectors.toList());

        //ID非法，非数字
        if (CollectionUtils.isEmpty(solutionIdsList)) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId非法，多个参数以;分割");
        }

        //1:修改为通过方案ID集合 批查询
        List<Solution> solutions = solutionService
                .findBySolutionIdsAndNotDel(solutionIdsList, DeleteEnum.NOT_DEL.getDbValue());

        //2:修改为通过方案ID集合 查询未删除的库存
        List<SolutionSku> solutionSkuList = solutionSkuService
                .findBySolutionIdsAndNotDel(solutionIdsList, DeleteEnum.NOT_DEL.getDbValue());

        //3:通过方案ID对库存进行分组
        Map<Long, List<SolutionSku>> skuMap = solutionSkuList.parallelStream()
                .collect(Collectors.groupingBy(sku -> sku.getSolutionId()));

        List<SolutionSkuResp> resultList = new ArrayList<>();

        //4:封装响应（方案以及方案对应的SKU）
        solutions.forEach(solution -> {
            SolutionSkuResp response = new SolutionSkuResp();
            response.setSolutionId(solution.getSolutionId());
            response.setSolutionName(solution.getSolutionName());

            Long solutionId = solution.getSolutionId();
            List<SkuBean> skuBeanList = new ArrayList<>();

            //Map分组为方案Id，获取对应方案ID的SKU集合封装
            if (MapUtils.isNotEmpty(skuMap)) {
                List<SolutionSku> solutionSkus = skuMap.get(solutionId);
                solutionSkus.parallelStream().filter(solutionSku -> solutionSku != null).map(solutionSku -> {
                    SkuBean skuBean = new SkuBean();
                    skuBean.setSkuId(solutionSku.getSkuId());
                    skuBean.setSkuName(solutionSku.getSkuName());
                    skuBean.setStatus(solutionSku.getStatus());
                    return skuBean;
                }).forEach(skuBean -> skuBeanList.add(skuBean));
            }
            response.setSkuList(skuBeanList);
            resultList.add(response);
        });
        return resultList;
    }

    public void removeSkus(SolutionSkuDelReq req) {
        if (!NumberHelper.validatePositive(req.getSolutionId())) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        if (CollectionUtils.isEmpty(req.getSkuIds())) {
            throw new BizException(Meta.CODE_451.getCode(), "skuIds不能为空");
        }
        if (StringUtils.isBlank(req.getOperator())) {
            throw new BizException(Meta.CODE_451.getCode(), "operator不能为空");
        }
        Integer count = solutionSkuService
                .updateIsDel(req.getSolutionId(), req.getSkuIds(), DeleteEnum.IS_DEL.getDbValue(), req.getOperator());
        if (count <= 0) {
            throw new BizException(SqlEnum.FAIL.getCode(), "没有可删除的数据");
        }
    }

    public void importSkus(SolutionSkuImportReq req) {
        if (StringUtils.isBlank(req.getOperator())) {
            throw new BizException(Meta.CODE_451.getCode(), "operator不能为空");
        }
        if (!NumberHelper.validatePositive(req.getSolutionId())) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        if (CollectionUtils.isEmpty(req.getSkus())) {
            throw new BizException(Meta.CODE_451.getCode(), "skus不能为空！");
        }
        Long solutionId = req.getSolutionId();
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(SqlEnum.FAIL.getCode(), "该方案不存在！");
        }
        List<SolutionSku> solutionSkus = new ArrayList<>();
        SolutionSku solutionSku;
        String operator = req.getOperator();
        for (SkuBean skuBean : req.getSkus()) {
            solutionSku = solutionSkuService.findBySolIdAndSkuId(solutionId, skuBean.getSkuId());
            if (solutionSku != null) {
                solutionSkuService.deleteById(solutionSku.getId());
            }
            solutionSku = new SolutionSku();
            solutionSku.setIsDel(DeleteEnum.NOT_DEL.getDbValue());
            solutionSku.setSolutionId(solutionId);
            solutionSku.setSkuId(skuBean.getSkuId());
            solutionSku.setSkuName(skuBean.getSkuName());
            solutionSku.setStatus(skuBean.getStatus());
            solutionSku.setCreateTime(new Date());
            solutionSku.setCreateUserName(operator);
            solutionSkus.add(solutionSku);
        }
        solutionSkuService.insertBatch(solutionSkus);
    }
}
